<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col
        :span="24"
        :xs="24"
      >
        <!-- 数据筛选表单 -->
        <el-form
          ref="queryForm"
          :model="queryParams"
          :inline="true"
          label-width="100px"
          class="form"
        >
          <!-- 数据筛选表单组件 -->
          <el-form-item
            :label="$t('usermanage.username')"
            prop="userName"
          >
            <el-input
              v-model="queryParams.user.userName"
              :placeholder="$t('usermanage.usernameplaceholder')"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item
            :label="$t('status')"
            prop="status"
          >
            <el-select
              v-model="queryParams.user.status"
              size="small"
              :placeholder="$t('usermanage.userstatusplaceholder')"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <!-- 数据筛选操作按钮 -->
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              style="margin-left:30px;"
              @click="handleQuery"
            >
              {{ $t('query') }}
            </el-button>
            <el-button
              icon="el-icon-refresh"
              size="mini"
              @click="resetQuery"
            >
              {{ $t('reset') }}
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 数据操作按钮 -->
        <el-row :gutter="20">
          <el-col :span="3">
            <el-button
              type="primary"
              icon="el-icon-plus"
              style="margin-left:20px;width:130px;"
              @click="handleAdd"
            >
              {{ $t('usermanage.adduser') }}
            </el-button>
          </el-col>
        </el-row>

        <!-- 数据表格 -->
        <el-table
          v-loading="loading"
          :data="userList"
          style="margin-right:40px;margin-left:20px;width:96%"
        >
          <!-- 数据表格列 -->
          <el-table-column
            :label="$t('usermanage.userid')"
            align="center"
            prop="id"
            width="80"
          />
          <el-table-column
            :label="$t('usermanage.username')"
            align="center"
            prop="userName"
          />
          <el-table-column
            :label="$t('usermanage.usernickname')"
            align="center"
            prop="nickName"
          />
          <el-table-column
            :label="$t('status')"
            align="center"
            prop="status"
          >
            <template slot-scope="scope">
              <el-tag
                v-if="scope.row.status === 0"
                size="small"
                type="success"
              >
                {{ $t('enabled') }}
              </el-tag>
              <el-tag
                v-else-if="scope.row.status === 1"
                size="small"
                type="danger"
              >
                {{ $t('disabled') }}
              </el-tag>
            </template>
          </el-table-column>
          <!-- 数据行操作按钮 -->
          <el-table-column
            :label="$t('operation')"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="small"
                type="text"
                icon="el-icon-key"
                @click="handleRole(scope.row)"
              >
                {{ $t('usermanage.assignroles') }}
              </el-button>
              <el-button
                size="small"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >
                {{ $t('edit') }}
              </el-button>
              <el-button
                size="small"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >
                {{ $t('delete') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 数据分页加载 -->
        <el-pagination
          :current-page="current"
          :page-sizes="[5, 10, 50, 100]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="margin-left:350px;margin-top:5px;"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <!-- 添加修改user对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <!-- 数据编辑表单组件 -->
        <el-form-item
          :label="$t('usermanage.username')"
          prop="userName"
        >
          <el-input
            v-model="form.userName"
            :placeholder="$t('usermanage.usernameplaceholder')"
          />
        </el-form-item>
        <el-form-item
          :label="$t('usermanage.usernickname')"
          prop="nickName"
        >
          <el-input
            v-model="form.nickName"
            :placeholder="$t('usermanage.usernicknameplaceholder')"
          />
        </el-form-item>
      </el-form>
      <!-- 数据提交操作按钮 -->
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="submitForm"
        >
          {{ $t('submit') }}
        </el-button>
        <el-button @click="cancel">
          {{ $t('cancel') }}
        </el-button>
      </div>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      :title="roleTitle"
      :visible.sync="roleDialogFormVisible"
      width="300px"
    >
      <el-form :model="roleForm">
        <el-tree
          ref="roleTree"
          :data="roleTreeData"
          show-checkbox
          :check-strictly="checkStrictly"
          node-key="id"
          :default-expand-all="true"
          :default-checked-keys="defaultRoles"
          :props="defaultProps"
        />
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="roleDialogFormVisible = false">
          {{ $t('submit') }}
        </el-button>
        <el-button
          type="primary"
          @click="submitAuthRole"
        >
          {{ $t('cancel') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUserByPage, getUser, addUser, updateUser, deleteUser, authRole,getUserRoles } from '@/api/system/user'
import { listAllRole } from '@/api/system/role';
export default {
  name: 'User',
  data() {
    return {
      // 默认选中的角色
      defaultRoles:[],
      // 状态类型
      statusOptions: [
        {
          value: 0,
          label: this.$t('enabled')
        },
        {
          value: 1,
          label: this.$t('enabled')
        }
      ],
      // User类型
      typeOptions: undefined,
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 当前页
      current: 0,
      // 每页数据量
      size: 0,
      // User表格数据
      userList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 数据查询参数
      queryParams: {
        current: 1,
        size: 5,
        user:{
            userName: null,
            status: null
        }
      },
      // 数据编辑表单
      form: {},
      // 表单数据校验规则
      rules: {
        userName: [
          { required: true, message: this.$t('usermanage.usernamerules'), trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: this.$t('usermanage.usernicknamerules'), trigger: 'blur' }
        ]
      },
      roleDialogFormVisible: false,
      defaultProps: {
        label: 'roleKey'
      },
      roleForm: {},
      roleTreeData: [],
      checkStrictly: true,
      roleTitle: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询User数据列表 */
    getList() {
      this.loading = true
      // console.log(this.language)
      listUserByPage(this.queryParams).then((response) => {
        this.userList = response.data.records
        this.total = Number(response.data.total)
        this.pageNum = this.queryParams.pageNum
        this.pageSize = this.queryParams.pageSize
        this.loading = false
      })
    },
    /** 处理分页 */
    handleSizeChange(val) {
      this.queryParams.size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.queryParams.current = val
      this.getList()
    },

    /** 数据编辑对话框取消按钮 */
    cancel() {
      this.open = false
      this.resetForm()
    },

    /** 数据编辑表单清空 */
    resetForm() {
      this.form = {
        userId: null,
        userName: null,
        nickName: null,
        status: null
      }
    },

    resetRoleForm() {
      this.roleForm = {
        userId: null,
        roleIds: []
      }
    },

    /** 数据筛选参数重置按钮 */
    resetQueryParams() {
      this.queryParams.current = 1
      this.queryParams.size = 5
    },

    /** 数据筛选搜索按钮 */
    handleQuery() {
      this.getList()
      this.resetQueryParams()
      this.$message.success(this.$t('querysuccess'))
    },

    /** 数据筛选重置按钮 */
    resetQuery() {
        this.queryParams = {
        current: 1,
        size: 5,
        // user:null
      }
      this.getList()
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.resetForm()
      this.open = true
      this.title = this.$t('usermanage.addTitle')
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.resetForm()
      getUser(row.id).then((response) => {
        this.form = response.data
        this.open = true
        this.title = this.$t('usermanage.editTitle')
      })
    },

    /** 数据提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.userId === null) {
            addUser(this.form).then((response) => {
              this.$message.success(this.$t('addsuccess'))
              this.open = false
              this.title = ''
              this.getList()
            })
          } else {
            // console.log(this.form)
            updateUser(this.form).then((response) => {
              this.$message.success(this.$t('editsuccess'))
              this.open = false
              this.title = ''
              this.getList()
            })
          }
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm(
        this.$t('deletewarning1') + row.userName + '"', this.$t('warning'), {
          confirmButtonText: this.$t('yes'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        })
        .then(function() {
          return deleteUser(row.id)
        })
        .then(() => {
          this.getList()
          this.$message.success(this.$t('deletesuccess'))
        })
        .catch(() => {})
    },

    /** 处理分配角色 */
    handleRole(row) {
      this.roleForm=row
      // this.roleForm.id = row.id
      this.roleTitle = this.$t('usermanage.foruser') + row.nickName + this.$t('usermanage.giverole'),
      this.roleDialogFormVisible = true
      listAllRole().then((response) => {
        this.roleTreeData = response.data
      })
      //获取该用户已有的roleId
      getUserRoles(this.roleForm.id).then((response)=>{
        var roles = response.data
        this.defaultRoles = roles.map((item) => item.roleId)
      })
    },
    /** 提交分配角色表单 */
    submitAuthRole() {
      this.roleForm.roleIds = this.$refs.roleTree.getCheckedKeys()
      // console.log(this.roleForm.roleIds)
      authRole(this.roleForm).then((response) => {
        this.$message.success(this.$t('editsuccess'))
        this.roleDialogFormVisible = false
        this.resetRoleForm()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.form {
  border: 2px dashed rgb(211, 211, 211);
  padding: 20px;
  padding-bottom: 0px;
  margin: 10px 20px 20px 20px;
}
</style>